/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package restService;

import java.io.IOException;
import java.util.List;
import javax.security.auth.login.LoginException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import net.elbandi.pve2api.Pve2Api;
import net.elbandi.pve2api.data.VmOpenvz;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * REST Web Service
 *
 * @author EleygiTheWane
 */
@Path("deleteVM")
public class DeleteVMResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of DeleteVMResource
     */
    public DeleteVMResource() {
    }

    /**
     * Retrieves representation of an instance of restService.DeleteVMResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("application/json")
    public String getJson() {
        //TODO return proper representation object
        throw new UnsupportedOperationException();
    }

    /**
     * PUT method for updating or creating an instance of DeleteVMResource
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("application/json")
    public JSONObject putJson(String content) throws JSONException, LoginException, IOException {
        JSONObject request = new JSONObject(content);
        System.out.println("Ce qu'on a recu en string "+ content);
        
        JSONObject result = new JSONObject();
        result.put("result", "false");
        
        boolean isExists = false;
        
        //connexion à Proxmox
        Pve2Api api = new Pve2Api("192.168.100.55", "root", "pam", "passpass");
        api.login();
        System.out.println("login ok");
        
        //Teste si le vmid existe
        List<VmOpenvz> existingVM = api.getOpenvzCTs("proxmox");
        for(int i=0; i<existingVM.size(); i++){
            if(existingVM.get(i).getVmid() == request.optInt("vmid"))
                isExists = true;
        }
        if(isExists == true){
            api.deleteOpenvz("proxmox", request.optInt("vmid"));  
            System.out.println("Suppression de la VM "+ request.optInt("vmid"));
            result.put("result", "true");
        }
        else{
            System.out.println("La VM "+ request.optInt("vmid")+" n'existe pas");
            result.put("result", "false");            
        }
        
        return result;
    }
}
